package com.xbongbong.crm.handle.analysis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.DetaPhonePojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.CommuicatePlanErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.enums.PhoneExtEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author sunshaoxiang
 * @ClassName CommunicatePlanDetailAnalysisDataHandler
 * @Description 访客计划详情页解析数据handler
 * @Date 2022/5/24 19:28
 * @Version 1.0
 **/
@Component("communicatePlanDetailAnalysisDataHandler")
public class CommunicatePlanDetailAnalysisDataHandler {

    public static final Logger LOGGER = LoggerFactory.getLogger(CommunicatePlanDetailAnalysisDataHandler.class);

    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private CommonHelp commonHelp;

    /**
     * 访客计划详情页客户处理
     * @param paasFormDataEntityExt 数据库中数据，
     * @param businessType
     * @param corpid
     * @param explainMap
     * @param formId
     * @param handlerExplainDTO
     * @return data 需要返回的数据
     * @author 吴峰
     * @date 2022/9/2 13:39
     * @throws XbbException
     */
    public JSONObject handleDetailSpecialField(PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType, String corpid, Map<String, FieldAttrEntity> explainMap, Long formId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        JSONObject data = new JSONObject();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("planId", paasFormDataEntityExt.getId());
        List<CommunicatePlanUserEntity> communicatePlanUserEntityList = communicatePlanUserModel.findEntitys(param);
        StringBuilder executorName = new StringBuilder();
        Set<String> executorIdSet = new HashSet<>();
        Map<String, CommunicatePlanUserEntity> planUserMap = new HashMap<>();
        communicatePlanUserEntityList.forEach(communicatePlanUserEntity -> executorIdSet.add(communicatePlanUserEntity.getUserId()));
        communicatePlanUserEntityList.forEach(communicatePlanUserEntity -> planUserMap.put(communicatePlanUserEntity.getUserId(), communicatePlanUserEntity));
        for (String id : executorIdSet) {
            CommunicatePlanUserEntity communicatePlanUserEntity = planUserMap.get(id);
            String userName = communicatePlanUserEntity.getUserName();
            executorName.append(userName).append(StringConstant.COMMA);
        }
        if (!communicatePlanUserEntityList.isEmpty()) {
            executorName.deleteCharAt(executorName.length() - 1);
        }
        data.put(CommunicatePlanEnum.EXECUTOR.getAttr(), executorName.toString());
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), 0L);
        PaasFormDataEntityExt customerEntityExt = customerModel.getByKey(customerId, corpid);
        if (Objects.isNull(customerEntityExt)) {
            throw new XbbException(CommuicatePlanErrorCodeEnum.API_ERROR_214009);
        }
        JSONObject customerData = customerEntityExt.getData();
        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(customerData, CustomerManagementEnum.NAME.getAttr(), "");
        JSONObject addressJsonObject = FastJsonHelper.getJsonObjectOrDefaultFromFormData(customerData, CustomerManagementEnum.ADDRESS.getAttr(), new JSONObject());
        String addressStr = addressJsonObject.getOrDefault(PaasConstant.PROVINCE, "").toString() + addressJsonObject.getOrDefault(PaasConstant.CITY, "").toString() + addressJsonObject.getOrDefault(PaasConstant.DISTRICT, "").toString() + addressJsonObject.getOrDefault(PaasConstant.ADDRESS, "").toString();
        // 查询关联客户的解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(customerEntityExt.getFormId(), corpid);
        Map<String, FieldAttrEntity> customerExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(paasFormExplainEntity) && Objects.equals(paasFormExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
            String explains = paasFormExplainEntity.getExplains();
            if (Objects.nonNull(explains)) {
                customerExplainMap = ExplainUtil.getExplainMap(explains, null);
            }
        }
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(Collections.singletonList(customerEntityExt.getDataId()), corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), false, mainUserMap, coUserMap);
        handlerExplainDTO.setOwnerId(mainUserMap.get(customerEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(customerEntityExt.getDataId()));

        List<DetaPhonePojo> detaPhonePojos = cusCallPhone(customerData, RedundantTemplateTypeEnum.CUSTOMER.getCode(), corpid, customerExplainMap, handlerExplainDTO);
        JSONArray phoneArr = new JSONArray();
        packagePlanPhone(phoneArr, detaPhonePojos, customerName, addressStr);
        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> contactList = paasEsModel.selectByOneCondition(XbbRefTypeEnum.CONTACT.getCode(), ContactEnum.CUSTOMER_NAME.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_CONTACT);

        List<Long> formIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        contactList.forEach(item -> formIds.add(item.getFormId()));
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("formIdIn", formIds);
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormExplainEntity> explainList = paasFormExplainModel.findEntitys(params);
        Map<Long, Map<String, FieldAttrEntity>> formContactExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormExplainEntity explain : explainList) {
            Map<String, FieldAttrEntity> contactExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(explain) && Objects.equals(explain.getDel(), DelEnum.NORMAL.getDel())) {
                String explains = explain.getExplains();
                if (Objects.nonNull(explains)) {
                    contactExplainMap = ExplainUtil.getExplainMap(explains, null);
                }
                formContactExplainMap.put(explain.getFormId(), contactExplainMap);
            }
        }

        for (PaasFormDataEntityExt contact : contactList) {
            JSONObject contactData = contact.getData();
            String contactName = FastJsonHelper.getStringOrDefaultFromFormData(contactData, ContactEnum.NAME.getAttr(), "");
            JSONObject contactAddressJsonObject = FastJsonHelper.getJsonObjectFromFormData(contactData, ContactEnum.ADDRESS.getAttr());
            String contactAddressStr;
            try {
                contactAddressStr = contactAddressJsonObject.getString(PaasConstant.PROVINCE) + contactAddressJsonObject.getString(PaasConstant.CITY) + contactAddressJsonObject.getString(PaasConstant.DISTRICT) + contactAddressJsonObject.getString(PaasConstant.ADDRESS);
            } catch (Exception e) {
                contactAddressStr = "";
            }
            Map<Long, List<String>> contactMainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> contactCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formDataFormExplainHelper.getUserIdMap(Collections.singletonList(contact.getDataId()), corpid, XbbRefTypeEnum.CONTACT.getCode(), false, contactMainUserMap, contactCoUserMap);
            handlerExplainDTO.setOwnerId(contactMainUserMap.get(contact.getDataId()));
            handlerExplainDTO.setCoUserId(contactCoUserMap.get(contact.getDataId()));

            List<DetaPhonePojo> contactDetaPhonePojos = cusCallPhone(contactData, RedundantTemplateTypeEnum.CONTACT.getCode(), corpid, formContactExplainMap.get(contact.getFormId()), handlerExplainDTO);
            packagePlanPhone(phoneArr, contactDetaPhonePojos, contactName, contactAddressStr);
        }
        data.put(CommunicatePlanEnum.CONTACT_WAY.getAttr(), phoneArr);
        return data;
    }

    /**
     * 电话获取
     * 重构前对应 -> com.xbongbong.saas.help.SaasListHelp#cusCallPhone(com.alibaba.fastjson.JSONObject, java.lang.Integer, java.lang.String, java.util.Map, com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO)
     * @param dataList
     * @param code
     * @param corpid
     * @param explainMap
     * @param handlerExplainDTO
     * @return
     */
    private List<DetaPhonePojo> cusCallPhone(JSONObject dataList, int code, String corpid, Map<String, FieldAttrEntity> explainMap, HandlerExplainDTO handlerExplainDTO) {
        boolean isShow = false;
        boolean attrVisible = false;
        // 呼叫中心号码封装
        List<DetaPhonePojo> dial = new ArrayList<>();
        JSONArray phoneJsonArray = null;
        phoneJsonArray = dataList.getJSONArray(ContactEnum.PHONE.getAttr());
        attrVisible = commonHelp.attrCanSee(ContactEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
        if(attrVisible){
            List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(ContactEnum.PHONE.getAttr()).getSubForm().getItems();
            Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
            explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
            boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
            if(text2CanSee){
                isShow = true;
            }
        }
        // 当电话子表单完全不可见的时候，不能拨打
        if(!attrVisible){
            return dial;
        }
        phoneJsonArray = Objects.isNull(phoneJsonArray) ? new JSONArray() : phoneJsonArray;
        for (int i = 0; i < phoneJsonArray.size(); i++) {
            String name = phoneJsonArray.getJSONObject(i).getString("text_1");
            String tel = phoneJsonArray.getJSONObject(i).getString("text_2");
            DetaPhonePojo detaPhonePojo = new DetaPhonePojo();
            detaPhonePojo.setName(PhoneExtEnum.getByCode(name).getName());
            detaPhonePojo.setPhoneNum(tel);
            if (!isShow && tel != null) {
                String telNum;
                if (tel.length() > 5) {
                    telNum = tel.substring(0, 3) + "****" + tel.substring(tel.length() - 2, tel.length());
                } else {
                    telNum = "*****";
                }
                detaPhonePojo.setTelNum(telNum);
            } else {
                detaPhonePojo.setTelNum(tel);
            }
            dial.add(detaPhonePojo);
        }

        return dial;
    }

    /**
     * 封装电话返回
     *重构前 -> com.xbongbong.saas.help.ProDetailHandlerHelp#packagePlanPhone(com.alibaba.fastjson.JSONArray, java.util.List, java.lang.String, java.lang.String)
     * @param phoneArr       号码
     * @param detaPhonePojos pojo
     * @param name           名称
     * @param address        地址
     */
    private void packagePlanPhone(JSONArray phoneArr, List<DetaPhonePojo> detaPhonePojos, String name, String address) {
        for (DetaPhonePojo detaPhonePojo : detaPhonePojos) {
            JSONObject contactObj = new JSONObject();
            contactObj.put(StringConstant.PLAN_CONTACT_ATTR, name);
            String telNum = detaPhonePojo.getTelNum() == null ? "" : detaPhonePojo.getTelNum();
            contactObj.put(StringConstant.PLAN_PHONE_ATTR, detaPhonePojo.getName() + ": " + telNum);
            contactObj.put(StringConstant.PLAN_ADDRESS_ATTR, address);
            phoneArr.add(contactObj);
        }
    }
}
